package hanlen.mq.starter.support;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

/**
 * mq-spring-boot-starter
 *
 * @author MrYe
 * @date 2021-10-25 18:14
 */
@Slf4j
@UtilityClass
public class QueueUtil {

    private static ObjectMapper mapper;

    static {
        mapper = new ObjectMapper();
        // 对于空的对象转json的时候不抛出错误
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        // 允许属性名称没有引号
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        // 允许单引号
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        // 设置输入时忽略在json字符串中存在但在java对象实际没有的属性
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        // 设置输出时包含属性的风格
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    public static int getProcessors() {
        return Runtime.getRuntime().availableProcessors();
    }

    public static String toJsonString(Object val) {
        try {
            return mapper.writeValueAsString(val);
        } catch (JsonProcessingException e) {
            log.error("[{}] toJsonString error：{{}}", val.getClass().getSimpleName(), e);
            return null;
        }
    }

    public static Integer defaultIfNull(Object value, Integer defaultValue) {
        return null == value ? defaultValue : Integer.valueOf(value.toString());
    }

}
